package com.ruoyi.pg.answerSheet.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.pg.answerSheet.domain.PgAnswer;
import com.ruoyi.pg.answerSheet.domain.PgAnswerLog;
import com.ruoyi.pg.answerSheet.service.IPgAnswerLogService;
import com.ruoyi.pg.answerSheet.vo.PgAnswerVo;
import com.ruoyi.pg.answerSheet.mapper.PgAnswerMapper;
import com.ruoyi.pg.answerSheet.service.IPgAnswerService;
import com.ruoyi.pg.questionnaire.service.IPgQuestionService;
import com.ruoyi.pg.questionnaire.vo.PgQuestionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 答卷详情Service业务层处理
 *
 * @author Ming
 * @date 2025-08-22
 */
@Service
public class PgAnswerServiceImpl extends ServiceImpl<PgAnswerMapper, PgAnswer> implements IPgAnswerService {

    @Autowired
    private IPgQuestionService questionService;
    @Autowired
    private IPgAnswerLogService answerLogService;

    @Override
    public TableDataInfo<PgAnswerVo> queryList(PgAnswerVo entity) {
        Page<PgAnswerVo> page = this.baseMapper.queryList(PageUtils.buildPage(), entity);
        for (PgAnswerVo record : page.getRecords()) {
            if (ObjectUtil.isNotEmpty(record.getQuestionContent())) {
                record.setOptionList(Arrays.asList(record.getQuestionContent().split(",")));
            }
        }
        return PageUtils.buildDataInfo(page);
    }

    @Override
    public List<PgAnswerVo> queryAll(PgAnswerVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public PgAnswerVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public Integer completion(Long assId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ass_id", assId);
        queryWrapper.isNotNull("content");
        queryWrapper.eq("delete_status", "1");
        return this.baseMapper.selectCount(queryWrapper);
    }

    @Override
    public PgAnswer queryByIds(Long assId, Long questionId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ass_id", assId);
        queryWrapper.eq("question_id", questionId);
        queryWrapper.eq("delete_status", "1");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public int addOrEdit(PgAnswerVo entity) {
        PgAnswer pgAnswer = queryByIds(entity.getAssId(), entity.getQuestionId());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        PgAnswerLog answerLog = new PgAnswerLog();
        answerLog.setUserName(user.getUserName());
        Date operationTime = new Date();
        answerLog.setOperationTime(operationTime);
        // 转换时间格式为yyyy-MM-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String operationTimeStr = sdf.format(operationTime);
        PgQuestionVo pgQuestionVo = questionService.queryById(entity.getQuestionId());
        String questionTitle = ObjectUtil.isNotEmpty(pgQuestionVo.getTitle()) ? pgQuestionVo.getTitle() : "";
        if (ObjectUtil.isNotEmpty(pgAnswer)) {
            entity.setId(pgAnswer.getId());
            if (ObjectUtil.isNotEmpty(entity.getContent())) {
                answerLog.setRemark("用户" + user.getUserName() + "在" + operationTimeStr + "修改了" + questionTitle + "问卷");
            } else {
                answerLog.setRemark("用户" + user.getUserName() + "在" + operationTimeStr + "提交了" + questionTitle + "问卷");
            }
            answerLogService.save(answerLog);
            return baseMapper.updateById(entity);
        } else {
            answerLog.setRemark("用户" + user.getUserName() + "在" + operationTimeStr + "提交了" + questionTitle + "问卷");
            answerLogService.save(answerLog);
            return baseMapper.insert(entity);
        }
    }

    @Override
    public void saveBatch(PgAnswerVo entity) {
        if (CollectionUtil.isNotEmpty(entity.getQuestionList())) {
            for (PgQuestionVo pgQuestionVo : entity.getQuestionList()) {
                PgAnswerVo answerVo = new PgAnswerVo();
                answerVo.setAssId(entity.getAssId());
                answerVo.setSurveyId(pgQuestionVo.getSurveyId());
                answerVo.setQuestionId(pgQuestionVo.getId());
                if (pgQuestionVo.getQuestionType().equals("多选") && ObjectUtil.isNotEmpty(pgQuestionVo.getCheckAnswer())) {
                    answerVo.setContent(String.join(",", pgQuestionVo.getCheckAnswer()));
                } else {
                    answerVo.setContent(pgQuestionVo.getAnswer());
                    if (ObjectUtil.isNotEmpty(pgQuestionVo.getAnswerRemark()))
                        answerVo.setRemark(pgQuestionVo.getAnswerRemark());
                }
                addOrEdit(answerVo);
            }
            calculateScore(entity);
        }
    }

    @Override
    public void calculateScore(PgAnswerVo entity) {
        PgQuestionVo questionVo = new PgQuestionVo();
        questionVo.setSurveyTitle("B");
        questionVo.setQuestionType("自动计算得分");
        List<PgQuestionVo> pgQuestionVos = questionService.queryAll(questionVo);
        // 获取列表的id列表
        List<Long> questionIdList = pgQuestionVos.stream().map(PgQuestionVo::getId).collect(Collectors.toList());
        // 根据问卷题目id查询得分列表
        PgAnswerVo answerVo = new PgAnswerVo();
        answerVo.setQuestionIds(questionIdList);
        answerVo.setQuestionName("总计得分");
        List<PgAnswerVo> pgAnswerVos = baseMapper.queryList(answerVo);
        int score = 0;
        for (PgAnswerVo pgAnswerVo : pgAnswerVos) {
            if (ObjectUtil.isNotEmpty(pgAnswerVo.getContent())) score += Integer.parseInt(pgAnswerVo.getContent());
        }
        // 计算b模块总得分
        if (CollectionUtil.isNotEmpty(pgQuestionVos)) {
            PgAnswerVo answerVo1 = new PgAnswerVo();
            answerVo1.setAssId(entity.getAssId());
            answerVo1.setSurveyId(pgQuestionVos.get(pgQuestionVos.size() - 1).getSurveyId());
            answerVo1.setQuestionId(pgQuestionVos.get(pgQuestionVos.size() - 1).getId());
            answerVo1.setContent(String.valueOf(score));
            addOrEdit(answerVo1);
        }
        // 计算c1总得分
        answerVo.setQuestionIds(null);
        answerVo.setQuestionName("C1");
        answerVo.setAssId(entity.getAssId());
        List<PgAnswerVo> pgAnswerVos1 = baseMapper.queryList(answerVo);
        int score1 = 0;
        for (PgAnswerVo pgAnswerVo : pgAnswerVos1) {
            if (ObjectUtil.isNotEmpty(pgAnswerVo.getContent())) score1 += Integer.parseInt(pgAnswerVo.getContent());
        }
        questionVo.setSurveyTitle("老年人能力最终等级");
        questionVo.setQuestionType(null);
        List<PgQuestionVo> pgQuestionVos1 = questionService.queryAll(questionVo);
        if (CollectionUtil.isNotEmpty(pgQuestionVos1)) {
            PgAnswerVo answerVo1 = new PgAnswerVo();
            answerVo1.setAssId(entity.getAssId());
            answerVo1.setSurveyId(pgQuestionVos1.get(0).getSurveyId());
            answerVo1.setQuestionId(pgQuestionVos1.get(0).getId());
            int allScore = score1 + score;
            String content = "";
            if (allScore == 90) {
                content = "能力完好";
            } else if (allScore >= 66 && allScore < 90) {
                content = "能力轻度受损(轻度失能)";
            } else if (allScore >= 46 && allScore < 66) {
                content = "能力中度受报(中度失能)";
            } else if (allScore >= 30 && allScore < 45) {
                content = "能力重度受损(重度失能)";
            } else {
                content = "能力完全丧失(完全失能)";
            }
            answerVo1.setContent(content);
            answerVo1.setRemark(String.valueOf(allScore));
            addOrEdit(answerVo1);
        }
    }

    @Override
    public String generateString(Long projectCode, Long questionId) {
        String content = baseMapper.queryContent(questionId);
        Integer sequence = 1;
        if (ObjectUtil.isNotEmpty(content)) {
            String substring = "";
            // 截取字符串的后六位
            if (content.length() <= 6) {
                // 如果字符串长度小于等于6，则取整个字符串
                substring = content;
            } else {
                // 如果字符串长度大于6，则取后六位
                substring = content.substring(content.length() - 6);
            }
            sequence = Integer.parseInt(substring) + 1;
        }
        // 获取当前年月，格式为yyMM
        String yearMonth = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMM"));

        // 格式化流水号为4位数字，不足补0
        String formattedSequence = String.format("%06d", sequence);

        // 拼接最终字符串
        return "Pg_" + projectCode + "_" + yearMonth + "_" + formattedSequence;
    }

    @Override
    public PgAnswerVo queryScore(Long assId) {
        return baseMapper.queryScore(assId);
    }

    @Override
    public Boolean ifCompleteBySurveyId(Long surveyId, Long assId) {
        QueryWrapper<PgAnswer> queryWrapper = new QueryWrapper();
        queryWrapper.eq("survey_id", surveyId);
        queryWrapper.eq("ass_id", assId);
        queryWrapper.eq("delete_status", "1");
        Integer countAll = baseMapper.selectCount(queryWrapper);
        queryWrapper.isNull("content").or().eq("content", "");
        Integer count = baseMapper.selectCount(queryWrapper);
        if (countAll > 0 && count == 0) {
            return true;
        }
        return false;
    }
}
